package jsyf.oa.dao.system;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.dao.BaseJdbcDao;
import jsyf.oa.entity.system.DepartEntity;
import jsyf.oa.idao.BaseDao;
import jsyf.oa.ientity.IBaseEntity;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 徐波
 * @creat: 2017/11/23 0023 9:59
 * description:
 */
@Repository
public class DepartDao extends BaseDao{

    public DepartDao() {
        this.iBaseEntity = new DepartEntity();
    }

    @Override
    public IBaseEntity convertJson2Entity(JSONObject json) {
        return JSON.toJavaObject(json, DepartEntity.class);
    }

    public List<DepartEntity> getByPage(String condition, Object[] params, int requestPage, int pageSize) {
        List<DepartEntity> list = new ArrayList<>();
        List<IBaseEntity> iBaseEntityList = super.getIBaseEntityListByPage(condition,params,requestPage,pageSize);
        for (int i = 0; i < iBaseEntityList.size(); i++) {
            list.add((DepartEntity) iBaseEntityList.get(i));
        }
        return list;
    }

    public List<DepartEntity> getByCondition(String condition, Object[] params) {
        return getByPage(condition,params,1,Integer.MAX_VALUE);
    }

    public DepartEntity getById(String id) {
        return (DepartEntity) super.getIBaseEntityById(id);
    }

    public void getChildrenIds(String departId,List<String> listCompanyIds){
        DepartEntity departEntity = this.getById(departId);
        List<JSONObject> children = this.getJSONListByCondition(" AND DEL_FLAG=0 AND PARENT_ID = ? ",new Object[]{departEntity.getId()});
        if(children == null || children.size() == 0){

        }else{
            for (int i = 0; i < children.size(); i++) {
                String childrenDepartId = children.get(i).getString("id");
                listCompanyIds.add(childrenDepartId);
                getChildrenIds(childrenDepartId,listCompanyIds);
            }
        }
    }

    public Boolean sort(String departIds){
        List<String> list = BaseJdbcDao.stringToList(departIds);
        for (int i = 0; i < list.size(); i++) {
            JSONObject obj = new JSONObject();
            obj.put("ID",list.get(i));
            obj.put("SORT_NO",i);

            JSONObject objId = new JSONObject();
            objId.put("ID",list.get(i));
            super.update(iBaseEntity.getTableName(),obj,objId);
        }
        return true;
    }
}
